package cn.jimmie.lib.qlog.support;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Func :
 *
 * <p> Create Time:  2019-07-18 09:20 </p>
 * <p> @author Jimmie.Qian  </p>
 */
public final class AlException {
    private static final String NULL = "";

    public static String fullTrace(Throwable throwable) {
        if (throwable == null) return NULL;
        PrintWriter pw = null;
        String trace = NULL;
        try {
            StringWriter sw = new StringWriter();
            pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            trace = sw.toString();
        } catch (Exception ignored) {

        } finally {
            AlIO.close(pw);
        }
        return trace;
    }

    public static String trace(Throwable throwable, int len) {
        if (throwable == null) return NULL;
        StringBuilder builder = new StringBuilder();

        builder.append(throwable.toString()).append("\n\t");
        StackTraceElement[] trace = throwable.getStackTrace();
        int size = Math.min(trace.length, len);
        for (int i = 0; i < size; i++) {
            StackTraceElement element = trace[i];
            builder.append(element.toString()).append("\n\t");
        }
        return builder.toString();
    }

    public static String trace(Throwable e) {
        return trace(e, 2);
    }
}
